package service

import (
	"awesomeProject2/global"
	"awesomeProject2/model"
	"awesomeProject2/model/request"
	"awesomeProject2/model/response"
	"awesomeProject2/utils"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strconv"
	"strings"
	"time"
)

func GetProject(id uint) (err error, project response.ProjectResponse) {
	err = global.GVA_DB.Model(&model.AnnualProjectRecord{}).Select("annual_project_record.*, project.*").
		Joins("left join project on project.id = annual_project_record.project_id").
		Where("project.id = ?", id).First(&project).Error
	return err, project
}

func GetAllProjectsbq(id uint, year int) (error, interface{}, int64) {
	var data []response.ProjectResponse
	var total int64

	err := global.GVA_DB.Model(&model.AnnualProjectRecord{}).Select("annual_project_record.*, project.*").
		Joins("left join project on project.id = annual_project_record.project_id").
		Where("project.user_id = ? AND YEAR(project.start_time) <= ? AND YEAR(project.end_time) >= ? And annual_project_record.year < ?", id, year, year, year).Find(&data).Count(&total).Error

	return err, data, total
}

func FillProject(c *gin.Context, projectRes *model.Project, annualProjectRecord *model.AnnualProjectRecord, data *request.Project) {
	utils.StructAssign(projectRes, data)
	_, current := model.GetCurrentTeacher(c)
	timeTemplate1 := "2006-01"

	start, _ := time.ParseInLocation(timeTemplate1, data.ProjectTimeList[0], time.Local)
	end, _ := time.ParseInLocation(timeTemplate1, data.ProjectTimeList[1], time.Local)
	projectRes.StartTime = start
	projectRes.EndTime = end
	projectRes.ProjectTime = strings.Join(data.ProjectTimeList, "至")

	projectRes.Owner = current.TeacherName
	projectRes.UserId = current.UserId

	annualProjectRecord.ProjectFile = strings.Join(data.ProjectFileList, ",")
	annualProjectRecord.ProjectAccumulatedFunds = data.ProjectAccumulatedFunds
	annualProjectRecord.ProjectMoney = data.ProjectMoney
	annualProjectRecord.Year = uint(data.Year)
	annualProjectRecord.ProjectId = data.ID

}

func GetAllProjects(id uint, year int) (error, interface{}, int64) {
	var data []response.ProjectResponse
	var total int64

	err := global.GVA_DB.Model(&model.AnnualProjectRecord{}).Select("annual_project_record.*, project.*").
		Joins("left join project on project.id = annual_project_record.project_id").
		Where("project.user_id = ? AND annual_project_record.year = ?", id, year).Find(&data).Count(&total).Error

	return err, data, total
}

func GetProjectsDynamic(info request.ProjectSearchInfo) (err error, list []response.ProjectResponse, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.PageNum - 1)
	db := global.GVA_DB.Model(&model.AnnualProjectRecord{}).Select("annual_project_record.*, project.*").
		Joins("left join project on project.id = annual_project_record.project_id")

	if info.ProjectName != "" {
		db = db.Where("project_name LIKE ?", "%"+info.ProjectName+"%")
	}
	if info.TeacherName != "" {
		db = db.Where("owner LIKE ?", "%"+info.TeacherName+"%")
	}
	if info.Category != "" {
		db = db.Where("project_category = ?", info.Category)
	}
	if info.Level != "" {
		db = db.Where("project_level = ?", info.Level)
	}
	if info.Year != "" {
		year, _ := strconv.Atoi(info.Year)
		db = db.Where("year = ?", year)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Find(&list).Error
	return err, list, total
}

func CreateProject(project *model.Project, annualProjectRecord *model.AnnualProjectRecord) (err error) {
	// 传入 ProjectID 不需要新增project
	if annualProjectRecord.ProjectId != 0 {
		return global.GVA_DB.Create(annualProjectRecord).Error
	}
	// 开启事务
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Create(project).Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}
		annualProjectRecord.ProjectId = project.ID
		if err := tx.Create(&annualProjectRecord).Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}
		// 返回 nil 提交事务
		return nil
	})
	return err
}

func DeleteProject(id int) (err error) {
	return global.GVA_DB.Where("project_id = ?", id).Unscoped().Delete(&model.AnnualProjectRecord{}).Error
}

func UpdateProject(project *model.Project, annualProjectRecord *model.AnnualProjectRecord) (err error) {
	// 开启事务
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Where("id = ?", project.ID).Updates(project).Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}
		// 更新匹配的年度项目记录
		if err := tx.Where("project_id = ? AND year = ?", annualProjectRecord.ProjectId, annualProjectRecord.Year).Updates(annualProjectRecord).Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}
		// 返回 nil 提交事务
		return nil
	})
	return err
}
